/*
 * Copyright (c) 2005, 2014 vacoor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package org.vacoor.nothing.demo.jackson.streaming;


import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
import com.fasterxml.jackson.core.util.MinimalPrettyPrinter;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 */
public class JacksonStreamingDemo {
    public void testWrite() throws IOException {
        JsonFactory jf = new JsonFactory();
        FileOutputStream out = new FileOutputStream("test.json");
        JsonGenerator jg = jf.createGenerator(out, JsonEncoding.UTF8);
        //压缩输出,默认值
        jg.setPrettyPrinter(new MinimalPrettyPrinter());
        //格式化输出
        jg.setPrettyPrinter(new DefaultPrettyPrinter());
        //写入一个对象的开始
        jg.writeStartObject();
        jg.writeStringField("gender", "MALE");
        jg.writeBooleanField("verified", false);
        jg.writeNumberField("age", 30);
        //开始写入数组
        jg.writeArrayFieldStart("name");
        jg.writeString("yang");
        jg.writeString("vacoor");
        jg.writeEndArray();
        //写入一个对象字段的开始
        jg.writeObjectFieldStart("object");
        jg.writeBooleanField("verified", false);
        jg.writeEndObject();
        jg.writeEndObject();
        jg.flush();
        jg.close();
    }

    public void testRead() throws IOException {
        FileInputStream in = new FileInputStream("test.json");
        JsonFactory jf = new JsonFactory();
        JsonParser jp = jf.createParser(in);
//		jp.configure(JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER,true);
        //是否允许有//注释行/* */注释
        jp.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
        //将NaN(Not-a-Number)值作为一个合法的浮点值
        jp.configure(JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS, true);
        //字段名称是否允许不使用引号,JS允许,JSON规范不允许
        jp.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);

        //一个token是一个标志字符,eg:{,",[,],}
        JsonToken token = jp.nextToken();    //{ START_OBJECT  [ START_ARRAY "" VALUE_STRING
        while (token != null) {
            System.out.println(jp.getCurrentName());
            if ("sex".equals(jp.getCurrentName())) {
                //move to value
                jp.nextToken();
                System.out.println("sex=" + jp.getValueAsString());
                //move to end
                jp.nextToken();
            }
            token = jp.nextToken();
        }
    }
}
